import React, { Component } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'dva'
import { Card, Button, Form, Input, DatePicker, Spin, Select } from 'antd'
import MyPageTable from '@/components/MyPageTable'
import { onTableData } from '@/utils/utils.js'
import CopyToClipboard from '@/components/CopyToClipboard'
import moment from 'moment'

const { RangePicker } = DatePicker
const { Option } = Select
import { getTimeDistance } from '@/utils/utils'
import { exportToLocal } from '@/services/login'
import { message } from 'antd'

@connect(({ order, loading }) => ({
  ...order,
  loading: loading.effects['order/queryOpeGoingOverDueOrdersByCondition']
}))
@Form.create()
export default class Expires extends Component {
  state = {
    current: 1,
    datas: {},
    defaultValue: [
      moment(moment().format('YYYY-MM-DD')),
      moment(moment().format('YYYY-MM-DD'))
    ]
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'order/PlateformChannel'
    })
    this.onList(1, 10)
  }

  onList = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props
    const { defaultValue } = this.state
    const [statementTimeStart, statementTimeEnd] = defaultValue
    if (statementTimeStart !== 'Invalid date') {
      data.statementTimeStart = moment(statementTimeStart).format(
        'YYYY-MM-DD 00:00:00'
      )
      data.statementTimeEnd = moment(statementTimeEnd).format(
        'YYYY-MM-DD 23:59:59'
      )
    } else {
      data.statementTimeStart = ''
      data.statementTimeEnd = ''
    }
    dispatch({
      type: 'order/queryOpeGoingOverDueOrdersByCondition',
      payload: {
        pageSize,
        pageNumber,
        ...data
      }
    })
  }

  rangePickerChange = (data, datastrings) => {
    console.log('rangePickerChange', data, datastrings)
    if (!data.length) {
      this.props.form.setFieldsValue({
        createDate: []
      })
      this.setState({
        defaultValue: [
          moment(datastrings[0]).format('YYYY-MM-DD'),
          moment(datastrings[1]).format('YYYY-MM-DD')
        ]
      })
    } else {
      this.setState({
        defaultValue: [
          moment(datastrings[0]).format('YYYY-MM-DD'),
          moment(datastrings[1]).format('YYYY-MM-DD')
        ]
      })
    }
  }

  handleSubmit = e => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      // const [statementTimeStart, statementTimeEnd] = this.state.defaultValue
      // values.statementTimeStart = statementTimeStart
      // values.statementTimeEnd = statementTimeEnd
      this.setState(
        {
          datas: { ...values }
        },
        () => {
          this.onList(1, 10, { ...values })
        }
      )
    })
  }

  // 按条件查询，今日到期和明日到期
  QueryByToDayAndTomorrow = type => {
    this.props.form.validateFields((err, values) => {
      let createDate = []
      const nowRange = [
        moment(moment().format('YYYY-MM-DD')),
        moment(moment().format('YYYY-MM-DD'))
      ]
      const tomorrowRange = [
        moment(
          moment()
            .add(1, 'days')
            .format('YYYY-MM-DD')
        ),
        moment(
          moment()
            .add(1, 'days')
            .format('YYYY-MM-DD')
        )
      ]
      if (type === 'now') {
        createDate = nowRange
      } else if (type === 'tomorrow') {
        createDate = tomorrowRange
      }
      this.props.form.setFieldsValue(
        {
          createDate
        },
        () => {
          this.setState(
            {
              defaultValue: type === 'now' ? nowRange : tomorrowRange,
              datas: { ...values }
            },
            () => {
              this.onList(1, 10, { ...values })
            }
          )
        }
      )
    })
  }

  exportToLocalByCondition = e => {
    e.preventDefault()
    let data = {}
    const { dispatch } = this.props
    const { defaultValue } = this.state
    const [statementTimeStart, statementTimeEnd] = defaultValue
    if (statementTimeStart !== 'Invalid date') {
      data.statementTimeStart = moment(statementTimeStart).format(
        'YYYY-MM-DD 00:00:00'
      )
      data.statementTimeEnd = moment(statementTimeEnd).format(
        'YYYY-MM-DD 23:59:59'
      )
    } else {
      data.statementTimeStart = ''
      data.statementTimeEnd = ''
    }
    this.props.form.validateFields((err, values) => {
      exportToLocal({ ...data, ...values,pageNumber: -1, pageSize: -1 }).then(res => {
        const objectURL = URL.createObjectURL(res)
        const btn = document.createElement('a')
        const body = document.querySelector('body')
        if (body) {
          body.appendChild(btn)
        }
        btn.download = `即将到期订单.xlsx`
        btn.href = objectURL
        btn.click()
        if (body) {
          body.removeChild(btn) // 删除标签
        }

        message.success('导出成功')
      })
    })
  }

  // table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current
      },
      () => {
        this.onList(e.current, 10, this.state.datas)
      }
    )
  }

  // 重置
  handleReset = e => {
    this.props.form.resetFields()
    const nowRange = [
      moment(moment().format('YYYY-MM-DD')),
      moment(moment().format('YYYY-MM-DD'))
    ]
    this.props.form.setFieldsValue(
      {
        createDate: nowRange
      },
      () => {
        this.setState(
          {
            defaultValue: nowRange
          },
          () => {
            this.onList(1, 10)
          }
        )
      }
    )
  }

  render() {
    const { conditionList, conditionTotal, loading } = this.props
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: conditionTotal,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      )
    }
    const columns = [
      {
        title: '订单编号',
        dataIndex: 'orderId',
        render: orderId => <CopyToClipboard text={orderId} />,
        width: '140px'
      },
      {
        title: '店铺名称',
        dataIndex: 'shopName',
        width: '140px'
      },
      // {
      //   title: '渠道来源',
      //   dataIndex: 'channelName',
      //   width: '10%',
      // },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: '200px'
      },
      // 接口BUG，currentPeriods字段返回始终为0
      // {
      //   title: '当前租期',
      //   dataIndex: 'currentPeriods',
      //   width: '60px',
      // },
      {
        title: '已支付期数/总期数',
        // dataIndex: 'currentPeriods',
        width: '110px',
        render: e => {
          return (
            <>
              <div
                style={{
                  width: 60,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap'
                }}
              >
                {e.payedPeriods}/{e.totalPeriods}
              </div>
            </>
          )
        }
      },
      {
        title: '总租金',
        width: '100px',
        render: e => {
          return <>{e.totalRentAmount}</>
        }
      },
      {
        title: '已付租金',
        width: '100px',
        render: e => {
          return <>{e.payedRentAmount}</>
        }
      },
      {
        title: '姓名',
        width: '100px',
        render: e => {
          return <>{e.realName}</>
        }
      },
      {
        title: '手机号',
        width: '130px',
        render: e => {
          return <>{e.telephone}</>
        }
      },
      {
        title: '起租时间',
        width: '120px',
        render: e => {
          return <>{e.rentStart}</>
        }
      },
      {
        title: '归还时间',
        width: '120px',
        render: e => {
          return <>{e.unrentTime}</>
        }
      },
      {
        title: '下单时间',
        dataIndex: 'placeOrderTime',
        width: '120px'
      },
      {
        title: '操作',
        fixed: 'right',
        width: '70px',
        align: 'center',
        render: e => {
          return (
            <div style={{ textAlign: 'center' }}>
              <a
                className="primary-color"
                // onClick={() => router.push(`/Order/Details?id=${e.orderId}&settlement=settlement`)}
                href={`#/Order/Expires/Details?id=${e.orderId}&settlement=settlement`}
                target="_blank"
              >
                详情
              </a>
            </div>
          )
        }
      }
    ]
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false}>
          <Form
            layout="inline"
            onSubmit={this.handleSubmit}
            style={{ marginBottom: 20 }}
          >
            <Form.Item label="商品名称">
              {getFieldDecorator(
                'productName',
                {}
              )(<Input allowClear placeholder="请输入商品名称" />)}
            </Form.Item>
            <Form.Item label="下单人姓名">
              {getFieldDecorator(
                'userName',
                {}
              )(<Input allowClear placeholder="请输入下单人姓名" />)}
            </Form.Item>
            <Form.Item label="下单人手机号">
              {getFieldDecorator(
                'telephone',
                {}
              )(<Input allowClear placeholder="请输入下单人手机号" />)}
            </Form.Item>
            <Form.Item label="订单编号">
              {getFieldDecorator(
                'orderId',
                {}
              )(<Input allowClear placeholder="请输入订单编号" />)}
            </Form.Item>
            <Form.Item label="账单日时间">
              {getFieldDecorator('createDate', {
                initialValue: this.state.defaultValue
              })(
                <RangePicker
                  style={{ width: 230 }}
                  allowClear
                  onChange={this.rangePickerChange}
                />
              )}
              {/* <RangePicker
                defaultValue={this.state.defaultValue}
                onChange={this.rangePickerChange}
                allowClear
              /> */}
            </Form.Item>

            <Form.Item label="付款状态">
              {getFieldDecorator('overDueStatus', {
                // initialValue: this.state.defaultValue
              })(
                <Select style={{ width: 150 }} placeholder="请选择付款状态">
                  <Option value="">全部</Option>
                  <Option value="2">已付款</Option>
                  <Option value="1">未付款</Option>
                </Select>
              )}
            </Form.Item>
            <div>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button htmlType="button" onClick={this.handleReset}>
                  重置
                </Button>
              </Form.Item>
              {/* 添加今日到期和明日到期按钮查询 */}
              <Form.Item>
                <Button
                  type="primary"
                  onClick={() => this.QueryByToDayAndTomorrow('now')}
                >
                  查询今日到期
                </Button>
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  onClick={() => this.QueryByToDayAndTomorrow('tomorrow')}
                >
                  查询明日到期
                </Button>
              </Form.Item>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={this.exportToLocalByCondition}
                >
                  导出
                </Button>
              </Form.Item>
            </div>
          </Form>
          <Spin spinning={loading}>
            <MyPageTable
              scroll={true}
              onPage={this.onPage}
              paginationProps={paginationProps}
              dataSource={onTableData(conditionList)}
              columns={columns}
            />
          </Spin>
        </Card>
      </PageHeaderWrapper>
    )
  }
}
